﻿using AntdUI;
using System;
using System.Drawing;
using System.Windows.Forms;

namespace JinYuan.ControlLib
{
    public class CustomDataGridView : DataGridView
    {
        private Color darkBackgroundColor = Color.FromArgb(18, 18, 18);
        private Color lightBackgroundColor = Color.White;
        private Color darkForeColor = Color.White;
        private Color lightForeColor = Color.Black;
        private Color darkHeaderBackColor = Color.FromArgb(30, 30, 30);
        private Color lightHeaderBackColor = Color.FromArgb(240, 240, 240);
        private Color darkSelectedCellColor = Color.FromArgb(64, 64, 64);
        private Color lightSelectedCellColor = Color.FromArgb(200, 200, 200);
        private Color darkSelectedColumnColor = Color.FromArgb(45, 45, 45);
        private Color lightSelectedColumnColor = Color.FromArgb(220, 220, 220);
        private Color darkButtonColor = Color.FromArgb(64, 64, 64);
        private Color lightButtonColor = Color.FromArgb(240, 240, 240);
        private Color darkComboBoxColor = Color.FromArgb(45, 45, 45);
        private Color lightComboBoxColor = Color.FromArgb(250, 250, 250);

        public CustomDataGridView()
        {
            InitializeComponent();
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.ResizeRedraw, true);
            this.SetStyle(ControlStyles.Selectable, true);
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            UpdateTheme(Config.IsDark);
        }

        private void InitializeComponent()
        {
            this.RowHeadersVisible = true;
            this.AllowUserToAddRows = false;
            this.AllowUserToDeleteRows = false;
            this.AllowUserToResizeRows = false;
            this.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            this.MultiSelect = false;
            this.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal;
            this.BorderStyle = BorderStyle.None;
            this.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            this.EnableHeadersVisualStyles = false;

            this.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.ColumnHeadersDefaultCellStyle.Font = new Font(this.Font.FontFamily, this.Font.Size, FontStyle.Bold);
            this.ColumnHeadersHeight = 30;

            this.RowHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.RowHeadersWidth = 50;

            // 设置默认的行高
            this.RowTemplate.Height = 28;
        }

        public void UpdateTheme(bool isDark)
        {
            // 基础颜色
            this.BackgroundColor = isDark ? darkBackgroundColor : lightBackgroundColor;
            this.ForeColor = isDark ? darkForeColor : lightForeColor;
            this.GridColor = isDark ? Color.DimGray : Color.LightGray;

            // 列头样式
            this.ColumnHeadersDefaultCellStyle.BackColor = isDark ? darkHeaderBackColor : lightHeaderBackColor;
            this.ColumnHeadersDefaultCellStyle.ForeColor = isDark ? darkForeColor : lightForeColor;
            this.ColumnHeadersDefaultCellStyle.SelectionBackColor = isDark ? darkSelectedColumnColor : lightSelectedColumnColor;
            this.ColumnHeadersDefaultCellStyle.SelectionForeColor = isDark ? darkForeColor : lightForeColor;

            // 行头样式
            this.RowHeadersDefaultCellStyle.BackColor = isDark ? darkHeaderBackColor : lightHeaderBackColor;
            this.RowHeadersDefaultCellStyle.ForeColor = isDark ? darkForeColor : lightForeColor;
            this.RowHeadersDefaultCellStyle.SelectionBackColor = isDark ? darkSelectedCellColor : lightSelectedCellColor;
            this.RowHeadersDefaultCellStyle.SelectionForeColor = isDark ? darkForeColor : lightForeColor;

            // 默认单元格样式
            this.DefaultCellStyle.BackColor = this.BackgroundColor;
            this.DefaultCellStyle.ForeColor = this.ForeColor;
            this.DefaultCellStyle.SelectionBackColor = isDark ? darkSelectedCellColor : lightSelectedCellColor;
            this.DefaultCellStyle.SelectionForeColor = isDark ? darkForeColor : lightForeColor;

            // 更新所有列的样式
            foreach (DataGridViewColumn column in this.Columns)
            {
                if (column is DataGridViewComboBoxColumn comboBoxColumn)
                {
                    // ComboBox列样式
                    comboBoxColumn.DefaultCellStyle.BackColor = isDark ? darkComboBoxColor : lightComboBoxColor;
                    comboBoxColumn.DefaultCellStyle.ForeColor = isDark ? darkForeColor : lightForeColor;
                    comboBoxColumn.DefaultCellStyle.SelectionBackColor = isDark ? darkSelectedCellColor : lightSelectedCellColor;
                    comboBoxColumn.DefaultCellStyle.SelectionForeColor = isDark ? darkForeColor : lightForeColor;
                    comboBoxColumn.FlatStyle = FlatStyle.Flat;
                }
                else if (column is DataGridViewButtonColumn buttonColumn)
                {
                    // Button列样式
                    DataGridViewCellStyle buttonStyle = new DataGridViewCellStyle();
                    buttonStyle.BackColor = isDark ? darkButtonColor : lightButtonColor;
                    buttonStyle.ForeColor = isDark ? darkForeColor : lightForeColor;
                    buttonStyle.SelectionBackColor = isDark ? darkSelectedCellColor : lightSelectedCellColor;
                    buttonStyle.SelectionForeColor = isDark ? darkForeColor : lightForeColor;
                    buttonStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    buttonColumn.DefaultCellStyle = buttonStyle;
                    buttonColumn.FlatStyle = FlatStyle.Flat;
                }
            }

            this.Invalidate();
        }

        protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex == -1 && e.ColumnIndex >= 0)
            {
                // 绘制列头
                e.PaintBackground(e.CellBounds, true);
                Rectangle newRect = new Rectangle(e.CellBounds.X + 2, e.CellBounds.Y + 2,
                    e.CellBounds.Width - 4, e.CellBounds.Height - 4);

                using (var brush = new SolidBrush(e.CellStyle.ForeColor))
                {
                    e.Graphics.DrawString(e.Value?.ToString(), this.ColumnHeadersDefaultCellStyle.Font,
                        brush, newRect, new StringFormat
                        {
                            Alignment = StringAlignment.Center,
                            LineAlignment = StringAlignment.Center
                        });
                }
                e.Handled = true;
            }
            else if (e.RowIndex >= 0 && e.ColumnIndex == -1)
            {
                // 绘制行头（行号）
                e.PaintBackground(e.CellBounds, true);
                Rectangle newRect = new Rectangle(e.CellBounds.X + 2, e.CellBounds.Y + 2,
                    e.CellBounds.Width - 4, e.CellBounds.Height - 4);

                string rowNumber = (e.RowIndex + 1).ToString();

                // 判断当前行是否被选中
                bool isSelected = this.Rows[e.RowIndex].Selected;
                Color textColor;

                if (isSelected)
                {
                    // 如果行被选中，使用选中状态的前景色
                    textColor = this.RowHeadersDefaultCellStyle.SelectionForeColor;
                }
                else
                {
                    // 如果行未被选中，使用普通状态的前景色
                    textColor = Config.IsDark ? darkForeColor : lightForeColor;
                }

                using (var brush = new SolidBrush(textColor))
                {
                    e.Graphics.DrawString(rowNumber, this.RowHeadersDefaultCellStyle.Font,
                        brush, newRect, new StringFormat
                        {
                            Alignment = StringAlignment.Center,
                            LineAlignment = StringAlignment.Center
                        });
                }
                e.Handled = true;
            }
            else if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                // 处理按钮列的绘制
                if (this.Columns[e.ColumnIndex] is DataGridViewButtonColumn)
                {
                    e.PaintBackground(e.CellBounds, true);
                    Rectangle buttonBounds = new Rectangle(e.CellBounds.X + 2, e.CellBounds.Y + 2,
                        e.CellBounds.Width - 4, e.CellBounds.Height - 4);

                    using (var buttonBrush = new SolidBrush(e.CellStyle.BackColor))
                    using (var textBrush = new SolidBrush(e.CellStyle.ForeColor))
                    {
                        // 绘制按钮背景
                        e.Graphics.FillRectangle(buttonBrush, buttonBounds);

                        // 绘制按钮文本
                        string buttonText = e.Value?.ToString() ?? string.Empty;
                        e.Graphics.DrawString(buttonText, this.Font, textBrush,
                            buttonBounds, new StringFormat
                            {
                                Alignment = StringAlignment.Center,
                                LineAlignment = StringAlignment.Center
                            });
                    }
                    e.Handled = true;
                }
                else
                {
                    base.OnCellPainting(e);
                }
            }
            else
            {
                base.OnCellPainting(e);
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            // 绘制列头底部边框
            using (var pen = new Pen(Config.IsDark ? Color.DimGray : Color.LightGray))
            {
                e.Graphics.DrawLine(pen, 0, this.ColumnHeadersHeight, this.Width, this.ColumnHeadersHeight);
            }
        }

        protected override void OnColumnHeadersHeightChanged(EventArgs e)
        {
            base.OnColumnHeadersHeightChanged(e);
            this.ColumnHeadersHeight = 30;
        }

        protected override void OnDataBindingComplete(DataGridViewBindingCompleteEventArgs e)
        {
            base.OnDataBindingComplete(e);

            // 重新应用主题样式
            UpdateTheme(Config.IsDark);
        }
    }
}
